var oCropCoords = {};
var oJcrop = false;


function cancel_crop() {
	oJcrop.destroy();
	$('#edit_media_tool_cont').html('');
}

function image_crop() {
	create_overlay(null, function(sId, oImg, oParams) {
		$.post('/admin/media_ajax/get_image_crop', {}, function(data) {
			$('#edit_media_tool_cont').html(data.sContent);
			
			init_jcrop();
			
			$(oImg).remove();
			$('#' + sId).remove();
		}, 'json');
	});
}



function init_jcrop() {
	oJcrop = $.Jcrop('#edit_media_image', {
		onChange: display_crop_coords,
		onSelect: display_crop_coords
	});
}


function display_crop_coords(c) {
	$('#image_crop_from_x').html(Math.round(c.x * oRatio.ratio));
	$('#image_crop_from_y').html(Math.round(c.y * oRatio.ratio));
	$('#image_crop_to_x').html(Math.round(c.x2 * oRatio.ratio));
	$('#image_crop_to_y').html(Math.round(c.y2 * oRatio.ratio));
	$('#image_crop_width').html(Math.round(c.w * oRatio.ratio));
	$('#image_crop_height').html(Math.round(c.h * oRatio.ratio));
	$('#image_crop_apply').show();
	oCropCoords = c;
}


function apply_crop() {
	
	create_overlay(null, function(sId, oImg, oPassThru) {
	
		oJcrop.destroy();
	
		var oParams = {
				sSrcImage : strip_domain($('#edit_media_image').attr('src')),
				iMediaId : oMedia.iMediaId,
				iFromX : $('#image_crop_from_x').html(),
				iFromY : $('#image_crop_from_y').html(),
				iWidth : $('#image_crop_width').html(),
				iHeight : $('#image_crop_height').html()
		};

	
		$.post('/admin/media_ajax/apply_crop', oParams, function(data) {
		
		
			if (data.sError) {
				$.prompt(data.sError);
				$(oImg).remove();
				$('#' + sId).remove();
				return;
			}
			
			append_history({ 
				sAction : data.sHistory,
				sImgSrc : data.sContent,
				iImgWidth : oParams.iWidth,
				iImgHeight : oParams.iHeight
			});
			
			$('#edit_media_image').attr('src', data.sContent).css({
				width : oParams.iWidth + 'px',
				height : oParams.iHeight + 'px'
			});
			
			
			set_zoom_level();
			publish_history();
			
			
			$(oImg).remove();
			$('#' + sId).remove();
			
		}, 'json');
	}, {});


	
	
}